package dnl.jexem.cmd;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Implements a <code>CommandExcecution</code> that executes on the local machine.
 *
 * @author Daniel Orr
 *
 */
public class LocalCommandExcecution extends BaseLocalCommandExecution {

    public static final int DEFAULT_IO_LISTENER_SLEEP = 5000;

    private ProcessIoHandler processIoHandler;

    private List<ProcessOutputListener> outputListeners;

    public LocalCommandExcecution(String... command) {
        super(command);
    }

    public LocalCommandExcecution(Command command) {
        super(command);
    }

    public void addOutputListener(ProcessOutputListener outputListener) {
        if (outputListeners == null) {
            outputListeners = new ArrayList<>();
        }
        outputListeners.add(outputListener);
    }

    @Override
    public String getOutput() {
        if (processIoHandler == null) {
            return null;
        }
        return processIoHandler.getStandardOut();
    }

    @Override
    public String getErrorOutput() {
        if (processIoHandler == null) {
            return null;
        }
        return processIoHandler.getStandardErr();
    }

    @Override
    public void kill() {
        try {
            super.kill();
        } finally {
            processIoHandler.kill();
        }
    }

    @Override
    protected void handleProcessIO(InputStream inputStream, InputStream errorStream, boolean block) throws IOException, InterruptedException {

        if (block) {
            processIoHandler = new BlockingIoHandler();
        } else {
            processIoHandler = new NonBlockingIoHandler(command, outputListeners);
        }
        processIoHandler.handleProcessIO(process.getInputStream(), process.getErrorStream());
        // process.waitFor() is included in the following call
        super.handleProcessTermination();
    }

}
